#include "cansettings.h"
#include "ui_cansettings.h"
#include<QComboBox>
#include<QIcon>
//类外初始化
CanSettings* CanSettings::instance = nullptr;
QMutex mutex;


CanSettings::CanSettings(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::CanSettings)
{
    ui->setupUi(this);







    this->setAttribute(Qt::WA_QuitOnClose,false);   //设置随主窗口关闭而关闭

    // QFileSystemModel *model = new QFileSystemModel;
    // model->setRootPath(QDir::currentPath());
    // QTreeView *tree = new QTreeView(splitter);
    // tree->setModel(model);

//

    //tree
    ui->treeView->setMaximumHeight(400);
    ui->treeView->header()->hide();
    //treemodel.setHorizontalHeaderLabels(QStringList()<<QStringLiteral("Networks"));
    QStandardItem *para_inv_root = treemodel.invisibleRootItem();
    QStandardItem *inv_root = new QStandardItem(QIcon(":/res/nw.ico"),QString("Networks"));
    para_inv_root->appendRow(inv_root);
    QStandardItem *item = new QStandardItem(QIcon(":/res/nw.ico"),QString("CAN Networks"));
    inv_root->appendRow(item); //添加第一层节点

    QFont *fontitem=new QFont();
    fontitem->setPointSize(14);
    item->setFont(*fontitem);

    item->setCheckable(true);
    for (int i = 0; i < 2; ++i)
    {
        QStandardItem *itemcan= new QStandardItem(QIcon(":/res/nw.ico"),QString("CAN")+QString("%0").arg(i+1));
        itemcan->setCheckable(true);
        itemcan->setFont(*fontitem);
        item->appendRow(itemcan); //
        QStandardItem *item_sub_nodes = new QStandardItem(QIcon(":/res/nodes.ico"),QString("Nodes")); //
        itemcan->appendRow(item_sub_nodes);
        item_sub_nodes->setCheckable(true);
         item_sub_nodes->setFont(*fontitem);
        QStandardItem *item_sub_daba = new QStandardItem(QIcon(":/res/db.ico"),QString("DateBases")); //
        itemcan->appendRow(item_sub_daba);
item_sub_daba->setCheckable(true);
           item_sub_daba->setFont(*fontitem);
        QStandardItem *item_sub_IG= new QStandardItem(QIcon(":/res/IG.ico"),QString("IG")); //
        itemcan->appendRow(item_sub_IG);
item_sub_IG->setCheckable(true);
            item_sub_IG->setFont(*fontitem);
        item_sub_IG->setCheckState(Qt::Checked);
    }

    ui->treeView->setStyle(QStyleFactory::create("windows"));
    ui->treeView->setModel(  &treemodel );
    ui->treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //set menu
    ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect( ui->treeView, &QTreeView::customContextMenuRequested, this, &CanSettings::onTreeViewMenuRequested);
    ui->treeView->expandAll();

    //add  tree tabview
    ui->tableView->setMinimumSize(700, 500);
     // ui->tableView->verticalHeader()->hide(); // hide row number

  //  QStandardItemModel *tableModel = new QStandardItemModel(this);
        ui->tableView->setModel(&tableModel); // recommend to set model before detail settings

    // set columns
    QStringList columnTitles;
    columnTitles << "id" << "name" <<"status" << "action";
    tableModel.setHorizontalHeaderLabels(columnTitles);
    //    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); // column fit the contents

    // add contents
    for(int i = 0; i < 7; i++)
    {
        tableModel.setItem(i, 0, new QStandardItem(QString::number(i + 1)));

        // 创建 QIcon 对象
        QIcon icon(":/res/nw.ico");  // 请将 "icon_path" 替换为实际的图标路径
        // 创建包含 QIcon 和字符串的 QStandardItem
        QStandardItem* item = new QStandardItem(icon, QString("hello qt tablview %1").arg(i));
        tableModel.setItem(i, 1, item);


        //tableModel->setItem(i, 1, new QStandardItem(QString("hello qt tablview %1").arg(i)));

        // Create a QComboBox for the status column
        QComboBox* comboBox = new QComboBox();
        comboBox->addItem("CAN1");
        comboBox->addItem("CAN2");

        // Set custom property
        comboBox->setProperty("id", i);
        comboBox->setProperty("name", QString("hello qt tablview %1").arg(i));

        // Insert the QComboBox at the status column
        ui->tableView->setIndexWidget(tableModel.index(i, 2), comboBox);


        // QPushButton *buttonsend = new QPushButton("send");
        // // set custom property
        // buttonsend->setProperty("id", i); // set custom property
        // buttonsend->setProperty("name", QString("hello qt tablview %1").arg(i));
        // // set click event
        // connect(buttonsend, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));

        // // notice every time insert the bWutton at the last line
        // ui->tableView->setIndexWidget(tableModel->index(tableModel->rowCount() - 1, 2), buttonsend);
        tableModel.setItem(i, 2, new QStandardItem("normal"));

        // add button to the last column
        QPushButton *button = new QPushButton("Send");
        // 根据状态设置按钮图标
        QIcon playIcon(":/res/send.ico"); // 播放状态的图标路径
        button->setIcon(playIcon);
        // set custom property
        button->setProperty("id", i); // set custom property
        button->setProperty("name", QString("hello qt tablview %1").arg(i));
        button->setProperty("status", "Send");

        // set click event
        connect(button, &QPushButton::clicked, this,&CanSettings::onTableBtnClicked);

        // notice every time insert the button at the last line
          ui->tableView->setIndexWidget(tableModel.index(tableModel.rowCount() - 1, 3), button);
    }

    //setting right key
    //set menu
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);//#设置只能选中整行
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect( ui->tableView, &QTableView::customContextMenuRequested, this, &CanSettings::onTableViewMenuRequested);

}



void CanSettings::onTableBtnClicked()
{
    QPushButton *button = (QPushButton *)sender();

    // 获取按钮的ID和状态
    int id = button->property("id").toInt();
    QString status = button->property("status").toString();
    // 根据当前状态切换按钮的文本和状态
    if (status == "Send") {
        button->setText("Stop");
        button->setProperty("status", "Stop");
        // 根据状态设置按钮图标
        QIcon playIcon(":/res/stop.ico"); // 播放状态的图标路径
        button->setIcon(playIcon);
        // 禁用按钮所在行的所有单元格编辑
        for (int col = 0; col < tableModel.columnCount(); ++col) {
            QModelIndex index = tableModel.index(id, col);
            QStandardItem *item = tableModel.itemFromIndex(index);
            if (item) {
                item->setEditable(false);
                item->setSelectable(false);
            }
        }
    } else {
        button->setText("Send");
        button->setProperty("status", "Send");
        // 根据状态设置按钮图标
        QIcon playIcon(":/res/send.ico"); // 播放状态的图标路径
        button->setIcon(playIcon);
        // 启用按钮所在行的所有单元格编辑
        for (int col = 0; col < tableModel.columnCount(); ++col) {
            QModelIndex index = tableModel.index(id, col);
            QStandardItem *item = tableModel.itemFromIndex(index);
            if (item) {
                item->setEditable(true);
                 item->setSelectable(true);
            }
        }
    }

    // qDebug() << button->property("id").toInt() ;
    // qDebug() << button->property("name").toString();
    // qDebug() << button->property("status").toString();
    if (button) {
        // 获取按钮的 custom property "id"
        int id = button->property("id").toInt();

        // 使用 id 来获取对应行的数据
        QStandardItemModel *tableModel = qobject_cast<QStandardItemModel *>(ui->tableView->model());
        if (tableModel) {
            QStandardItem *statusItem;
            QStandardItem *idItem = tableModel->item(id, 0);
            QStandardItem *nameItem = tableModel->item(id, 1);
            // 获取 status 列的值
            QComboBox *comboBox = qobject_cast<QComboBox *>(ui->tableView->indexWidget(tableModel->index(id, 2)));
            if (comboBox) {
                QString status = comboBox->currentText();
                statusItem = new QStandardItem(status);
            } else {
                statusItem = tableModel->item(id, 2);
            }

            // 打印数据
            qDebug() << "ID:" << idItem->text();
            qDebug() << "Name:" << nameItem->text();
            qDebug() << "Status:" << statusItem->text();
        }
    }
    // QMessageBox::warning(nullptr, "Warning!", "ok!");
    // QMessageBox::warning(nullptr, "Warning!", "ok!");
}

void CanSettings::deleteoneline()
{
    //弹出提示框，看是否删除数据
    QMessageBox message(QMessageBox::NoIcon, QString::fromLocal8Bit("TIPS"),
                        QString::fromLocal8Bit("DELETE ?"),
                        QMessageBox::Yes | QMessageBox::No, NULL);

    //如确认删除
    if(message.exec() == QMessageBox::Yes)
    {

            tableModel.removeRow( ui->tableView->currentIndex().row());
            qDebug()<<"del row..."<<ui->tableView->currentIndex().row();

    }
    //update
    updaterowsid();



  //  ui->removeRow(seletMouseRow);  //删除掉了表格信
}

void CanSettings::deleteallline()
{
    //弹出提示框，看是否删除 all数据
    QMessageBox message(QMessageBox::NoIcon, QString::fromLocal8Bit("TIPS"),
                        QString::fromLocal8Bit("DELETE all>>>>>>>>> ?"),
                        QMessageBox::Yes | QMessageBox::No, NULL);

    //如确认删除
    if(!(message.exec() == QMessageBox::Yes))
    {
        return;

    }
    QItemSelectionModel *model_selection = ui->tableView->selectionModel();
    QModelIndexList IndexList= model_selection->selectedIndexes();
    QMap<int,int>rowMap;
    foreach (QModelIndex index, IndexList)
    {
        if(! index.isValid()) return;
        if(index.column()!=0) continue;
        rowMap.insert(index.row(),0);
    }

    QMapIterator<int,int> Iterator(rowMap);
    Iterator.toBack();
    while(Iterator.hasPrevious())
    {
        Iterator.previous();
        int rowm=Iterator.key();
        qDebug()<<"del row..."<<rowm;
        tableModel.removeRow(rowm);
    }
    //update
    updaterowsid();

}

void CanSettings::addoneline()
{

    QMessageBox message(QMessageBox::NoIcon, QString::fromLocal8Bit("TIPS"),
                        QString::fromLocal8Bit("add one line ?"),
                        QMessageBox::Yes | QMessageBox::No, NULL);


    if(!(message.exec() == QMessageBox::Yes))
    {
        return;

    }

    int row = tableModel.rowCount();
    qDebug()<<"add lines"<<row;
    //tableModel.insertRow(row);



    tableModel.setItem(row, 0, new QStandardItem(QString::number(row + 1)));

    // 创建 QIcon 对象
    QIcon icon(":/res/nw.ico");  // 请将 "icon_path" 替换为实际的图标路径
    // 创建包含 QIcon 和字符串的 QStandardItem
    QStandardItem* item = new QStandardItem(icon, QString("new message %1").arg(row));
    tableModel.setItem(row, 1, item);
    QComboBox* comboBox = new QComboBox();
    comboBox->addItem("CAN1");
    comboBox->addItem("CAN2");

    // Set custom property
    comboBox->setProperty("id", row);
    comboBox->setProperty("name", QString("hello qt tablview %1").arg(row));

    // Insert the QComboBox at the status column
    ui->tableView->setIndexWidget(tableModel.index(row, 2), comboBox);
    tableModel.setItem(row, 2, new QStandardItem("normal"));

    // add button to the last column
    QPushButton *button = new QPushButton("Send");
    // 根据状态设置按钮图标
    QIcon playIcon(":/res/send.ico"); // 播放状态的图标路径
    button->setIcon(playIcon);
    // set custom property
    button->setProperty("id", row); // set custom property
    button->setProperty("name", QString("hello qt tablview %1").arg(row));
    button->setProperty("status", "Send");

    // set click event
    connect(button, &QPushButton::clicked, this,&CanSettings::onTableBtnClicked);

    // notice every time insert the button at the last line
    ui->tableView->setIndexWidget(tableModel.index(tableModel.rowCount() - 1, 3), button);
    //setting right key
    //set menu
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);//#设置只能选中整行
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect( ui->tableView, &QTableView::customContextMenuRequested, this, &CanSettings::onTableViewMenuRequested);

    //update
    updaterowsid();


}

void CanSettings::updaterowsid()
{
    int row = tableModel.rowCount();
    qDebug()<<"add lines"<<row;

     // QModelIndex index = curIndex.sibling(curIndex.row(), 0); // 获取同一行第0列
    //修改数据前后，用beginResetModel()和endResetModel()。
    //beginResetModel();    //通过这个告诉我要开始修改model了
    // if(!index.isValid()) {
    //     return;
    // }
    // m_data.clear();
    // for (int i = 0;i < allitems.count();++i) {
    //     m_data.append(allitems[i]);
    // }
    //endResetModel();    //通过这个告诉我修改model结束了

    // for(int i=0;i<row;++i)
    // {
    //     QStandardItem* item = new QStandardItem(QString::number(row + 1));
    //     tableModel.setItem(row, 0, item);
    // }
    int rowCount = ui->tableView->model()->rowCount(); // Get the row count of the model

    for (int i = 0; i < rowCount; i++) {
        QModelIndex index = ui->tableView->model()->index(i, 0); // Index of the ID column (assuming it's the first column)
        ui->tableView->model()->setData(index, i+1); // Set the ID value to be increasing starting from 1
    }
    int row1 = tableModel.rowCount();
    qDebug()<<"[lines]lines"<<row1;
   // endResetModel();    //


    ui->tableView->sortByColumn(0, Qt::SortOrder::AscendingOrder);
    ui->tableView->update();
}



void ClickDownloadButton()
{
     QMessageBox::warning(nullptr, "Warning!", "Failed to open the file!");
}

//onTableViewMenuRequested

void CanSettings::onTableViewMenuRequested(const QPoint &pos)
{
    QModelIndex curIndex =  ui->tableView->indexAt(pos);

    if (curIndex.isValid()) // 右键选中了有效index
    {

        QIcon delete1 = QApplication::style()->standardIcon(QStyle::SP_FileIcon);
            QIcon delete2 = QApplication::style()->standardIcon(QStyle::SP_FileIcon);

            // 创建菜单
            QMenu menu;
            menu.addAction(delete1, tr("增加"), this, &CanSettings::addoneline);
            menu.addSeparator();
            menu.addAction(delete1, tr("删除"), this, &CanSettings::deleteoneline);
            menu.addSeparator();
            menu.addAction(delete2, tr("删除所有行"), this, &CanSettings::deleteallline);
            menu.exec(QCursor::pos());


    }
}

void CanSettings::onTreeViewMenuRequested(const QPoint &pos)
{
    QModelIndex curIndex =  ui->treeView->indexAt(pos);

    if (curIndex.isValid()) // 右键选中了有效index
    {
        if(curIndex.data().toString()=="DateBases")
        {

            QIcon view = QApplication::style()->standardIcon(QStyle::SP_FileIcon);
            QIcon test = QApplication::style()->standardIcon(QStyle::SP_FileIcon);

            // 创建菜单
            QMenu menu;
            menu.addAction(view, tr("打开文件"), this, &CanSettings::onActionView);
            menu.addSeparator();
            menu.addAction(test, tr("测试"), this, &CanSettings::onActionTest);
            menu.exec(QCursor::pos());
        }

    }
}



void CanSettings::onActionView()
{
    QFont *fontitem=new QFont();
    fontitem->setPointSize(14);

    QModelIndex curIndex =  ui->treeView->currentIndex();
    QModelIndex index = curIndex.sibling(curIndex.row(), 0); // 获取同一行第0列
    if(index.isValid())
    {
        QString  fileName;

        fileName = QFileDialog::getOpenFileName(
            this,
            tr("Open ."),
            "D:/",
            tr("text files(*.odc );;All files(*.*)"));
        if (fileName.isEmpty()) {
            QMessageBox::warning(this, "Warning!", "Failed to open the file!");
        }
        else {
            QFileInfo fileInfo(fileName);
            QString fileName_name = fileInfo.baseName();

        //更新 treeview
            //
            QStandardItem *item_sub_db = new QStandardItem(QIcon(":/res/db.ico"),fileName_name); //
                item_sub_db->setFont(*fontitem);
        // 获取TreeView的model
        QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui->treeView->model());

            // 在树的根节点下查找要添加节点的父节点
            //QModelIndex rootIndex = model->index(0, 0); // 假设根节点在第一行第一列
            QStandardItem* rootNode = model->itemFromIndex(curIndex);
            // 检查是否有重复节点名
            bool duplicateFound = false;
            for (int row = 0; row < rootNode->rowCount(); ++row) {
                QStandardItem* childNode = rootNode->child(row, 0);
                if (childNode->text() == fileName_name) {
                    duplicateFound = true;
                    break;
                }
            }
            if (!duplicateFound) {
                rootNode->appendRow(item_sub_db);
            }

        }

        QMessageBox::information(this, tr("打开文件"), index.data().toString());
    }
}
void CanSettings::onActionTest()
{
    QMessageBox::information(this, tr("测试"), tr("test"));
}

// void CanSettings::contextMenuEvent(QContextMenuEvent *event) {
//     QPoint pos = event->pos();
//     QModelIndex index =  ui->treeView->indexAt(pos);

//     if (index.isValid()) {
//         QMenu *menu = new QMenu(this);
//         menu->addAction("exit");
//         menu->addAction("Action 2");
//         // 添加更多的菜单项...

//         menu->exec( ui->treeView->viewport()->mapToGlobal(pos));
//     }
// }

CanSettings::~CanSettings()
{
    delete ui;
}



//加锁的懒汉式实现
CanSettings* CanSettings::getInstance()
{
    //当多线程获取单例时有可能引发竞态条件
    static QMutex mutex;
    if(!instance)
    {
        QMutexLocker locker(&mutex);   //加锁,解决线程安全的问题
        if(!instance)
        {
            qDebug()<<"new Config";
            instance = new CanSettings;   //注意内存泄露问题
        }
    }
    return instance;
}
//点击某个节点
void CanSettings::on_treeView_clicked(const QModelIndex &index)
{
    QString  str;
    str += QStringLiteral("CHOUSE: %1\n row%2,column:%3\n").arg(index.data().toString()).arg(index.parent().data().toString());
    QMessageBox::information(this,"note",str);

}


void CanSettings::on_tableView_clicked(const QModelIndex &index)
{
    QString  str;
    str += QStringLiteral("CHOUSE table: %1\n ").arg(index.data().toString());
    qDebug()<<str;
  //  QMessageBox::information(this,"note",str);

}

